
package com.ruoyi.pay.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.pay.consts.ApiCodeEnum;
import com.ruoyi.pay.consts.CS;
import com.ruoyi.pay.domain.*;
import com.ruoyi.pay.mapper.MchAppMapper;
import com.ruoyi.pay.mapper.MchInfoMapper;
import com.ruoyi.pay.mapper.MchPayPassageMapper;
import com.ruoyi.pay.mapper.PayInterfaceConfigMapper;
import com.ruoyi.pay.model.params.IsvParams;
import com.ruoyi.pay.service.PayInterfaceDefineService;
import com.ruoyi.pay.service.impl.PayInterfaceConfigService;
import com.ruoyi.pay.utils.StringKit;
import com.ruoyi.pay.vo.ApiRes;
import com.ruoyi.rabbitMq.model.ResetIsvMchAppInfoConfigMQ;
import com.ruoyi.rabbitMq.send.IMQSender;
import com.ruoyi.system.mapper.SysUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;

/**
 * 服务商支付接口管理类
 *
 * @author zhuxiao
 * @site
 * @date 2021-04-27 15:50
 */
@RestController
@RequestMapping("/api/isv/payConfigs")
public class IsvPayInterfaceConfigController extends BaseController {

    @Autowired
    private PayInterfaceConfigService payInterfaceConfigService;

    @Resource
    private PayInterfaceConfigMapper payInterfaceConfigMapper;

    @Autowired
    private PayInterfaceDefineService payInterfaceDefineService;

    @Resource
    private MchPayPassageMapper mchPayPassageMapper;


    @Resource
    private MchAppMapper mchAppMapper;

    @Resource
    private MchInfoMapper mchInfoMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Autowired private IMQSender mqSender;

    private static final String CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final int KEY_LENGTH = 128;

    /**
     * <简述>根据商户号和接口类型查询支付接口配置信息
     * <详细描述>填写参数点击操作
     *
     * @param isvNo
     * @param ifCode
     * @return com.ruoyi.alipay.domain.ApiRes<com.ruoyi.alipay.domain.PayInterfaceConfig>
     * @author syf
     * @date 2025/1/13 15:41
     */
    @GetMapping("/{isvNo}/{ifCode}")
    public ApiRes<PayInterfaceConfig> getByMchNo(@PathVariable(value = "isvNo") String isvNo, @PathVariable(value = "ifCode") String ifCode) {
        PayInterfaceConfig payInterfaceConfig = payInterfaceConfigService.getByInfoIdAndIfCode(CS.INFO_TYPE_ISV, isvNo, ifCode);
        if (payInterfaceConfig != null) {
            if (StringUtils.isNotBlank(payInterfaceConfig.getIfParams())) {
                IsvParams isvParams = IsvParams.factory(payInterfaceConfig.getIfCode(), payInterfaceConfig.getIfParams());
                if (isvParams != null) {
                    payInterfaceConfig.setIfParams(isvParams.deSenData());
                }
            }
        }
        return ApiRes.ok(payInterfaceConfig);
    }

    /**
     * @Description: 服务商支付接口参数配置
     * @Date: 16:45 2021/4/27
     */
    @PostMapping("/save/{infoId}/{ifCode}")
    public ApiRes saveOrUpdate(@PathVariable(value = "infoId") String infoId, @PathVariable(value = "ifCode") String ifCode, @RequestBody PayInterfaceConfig payInterfaceConfig) {

        payInterfaceConfig.setInfoType(CS.INFO_TYPE_ISV);

        //添加更新者信息
        Long userId = LoginHelper.getUserId();
        String realName = LoginHelper.getUsername();
        payInterfaceConfig.setUpdatedUid(userId);
        payInterfaceConfig.setUpdateBy(realName);

        //根据 服务商号、接口类型 获取商户参数配置
        PayInterfaceConfig dbRecoed = payInterfaceConfigService.getByInfoIdAndIfCode(CS.INFO_TYPE_ISV, infoId, ifCode);
        //若配置存在，为saveOrUpdate添加ID，第一次配置添加创建者
        if (dbRecoed != null) {
            payInterfaceConfig.setId(dbRecoed.getId());

            // 合并支付参数
            payInterfaceConfig.setIfParams(StringKit.marge(dbRecoed.getIfParams(), payInterfaceConfig.getIfParams()));
        } else {
            payInterfaceConfig.setCreatedUid(userId);
            payInterfaceConfig.setCreatedBy(realName);
        }

         SysUser sysUser = sysUserMapper.selectUserById(Long.valueOf(infoId));
        // 保存或更新商户支付通道表:t_mch_pay_passage
        PayInterfaceDefine param = new PayInterfaceDefine();
        param.setIfCode(ifCode);
        PayInterfaceDefine en = payInterfaceDefineService.getPayInterfaceDefine(param);
        if (en == null || en.getWayCodes() == null){
            return ApiRes.fail(ApiCodeEnum.SYSTEM_ERROR, "未找到该支付接口");
        }
        mchPayPassageMapper.delete(MchPayPassage.gw().eq(MchPayPassage::getAppId, infoId).eq(MchPayPassage::getIfCode, ifCode));
        List<MchPayPassage> list = new ArrayList<>();
        //[{"wayCode": "ALI_JSAPI"}, {"wayCode": "ALI_WAP"}, {"wayCode": "ALI_BAR"}, {"wayCode": "ALI_APP"}, {"wayCode": "ALI_PC"}, {"wayCode": "ALI_QR"}, {"wayCode": "ALI_OC"}]
        for (Object jsonObject : en.getWayCodes()) {
            JSONObject obj = JSONObject.parseObject(jsonObject.toString());
            String wayCode = obj.getString("wayCode");
            MchPayPassage msg = new MchPayPassage();
            msg.setMchNo(infoId);
            msg.setAppId(infoId);
            msg.setIfCode(ifCode);
            //msg.setRate(payInterfaceConfig.getIfRate());
            msg.setRate(new BigDecimal(0));
            msg.setState((byte) 1);
            msg.setWayCode(wayCode);
            list.add(msg);
        }
        mchPayPassageMapper.insertBatch(list);
        // 保存或更新商户:t_mch_app
        MchApp mchApp = mchAppMapper.selectOne(MchApp.gw().eq(MchApp::getAppId, infoId));
        if (mchApp == null) {
            mchApp = new MchApp();
            mchApp.setAppId(infoId);
            mchApp.setMchNo(infoId);
            mchApp.setAppName(sysUser.getUserName());
            mchApp.setState((byte) 1);
            generateAndSetAppSecret(mchApp);
            mchAppMapper.insert(mchApp);
        }
        // 保存或更新商户:t_mch_info
        MchInfo mchInfo = mchInfoMapper.selectOne(MchInfo.gw().eq(MchInfo::getMchNo, infoId));
        if (mchInfo == null) {
            mchInfo = new MchInfo();
            mchInfo.setMchNo(infoId);
            mchInfo.setType((byte) 1);
            mchInfo.setState((byte) 1);
            mchInfo.setMchName(sysUser.getUserName());
            mchInfo.setMchShortName(sysUser.getNickName());
            mchInfo.setContactName(sysUser.getNickName());
            mchInfo.setContactTel(sysUser.getPhonenumber());
            mchInfoMapper.insert(mchInfo);
        }

        //查询支付方式
        boolean result = payInterfaceConfigMapper.insertOrUpdate(payInterfaceConfig);
        if (!result) {
            return ApiRes.fail(ApiCodeEnum.SYSTEM_ERROR, "配置失败");
        }
        // 推送mq到目前节点进行更新数据
         mqSender.send(ResetIsvMchAppInfoConfigMQ.build(ResetIsvMchAppInfoConfigMQ.RESET_TYPE_ISV_INFO, infoId, null, null));

        return ApiRes.ok();
    }

    public void generateAndSetAppSecret(MchApp mchApp) {
        String appSecret = generateRandomKey(KEY_LENGTH);
        mchApp.setAppSecret(appSecret);
    }

    /*
     * <简述>生成tappSecret
     * <详细描述>
     * @author syf
     * @date 2025/4/24 11:00
     * @param null
     * @return null
     */
    private String generateRandomKey(int length) {
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        return sb.toString();
    }

}
